package org.nerve.tinker.rpc.component;

import com.alibaba.fastjson.JSON;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.nerve.tinker.rpc.TinkerRequest;
import org.nerve.tinker.rpc.TinkerResponse;
import org.nerve.tinker.rpc.TinkerService;

/**
 * com.zeus.dpos.rpc.client
 * Created by zengxm on 2016/4/25.
 */
public class CommonRpcClient {

	protected TTransport transport=null;
	protected TinkerService.Client client;

	protected String host;
	protected int port;

	public CommonRpcClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	protected TProtocol getTProtocol() throws TTransportException {
		transport = new TFramedTransport(new TSocket(host, port));
		transport.open();
		return new TCompactProtocol(transport);
	}

	protected TinkerService.Client getClient() throws TTransportException {
		if(client==null)
			client=new TinkerService.Client(getTProtocol());

		return client;
	}


	protected TinkerRequest createRequest(Object data){
		return new TinkerRequest().setData(JSON.toJSONString(data));
	}

	public TinkerResponse action(Object data) throws TException {
		return getClient().action(createRequest(data));
	}



	public void close(){
		if(transport!=null && transport.isOpen())
			transport.close();
	}
}
